<template>
  <div class="createPost-container">
    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm">
      <div class="createPost-main-container">
        <el-col :span="12" :offset="6">
          <el-form-item label-width="110px" label="位置：" class="postInfo-container-item">
            <el-col :span="12">
                <el-select v-model="postForm.feature" placeholder="请选择位置">
                  <el-option
                    v-for="item in featureOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label-width="110px" label="投放区域：" class="postInfo-container-item" v-show="postForm.feature == 'HOMEPAGE_BANNERS'" prop="areaName">
            <el-col :span="12">
                <el-select v-model="postForm.areaName" filterable placeholder="请选择">
                  <el-option
                    v-for="item in areaOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
            </el-col>
          </el-form-item>

          <el-form-item label-width="110px" label="系统：" class="postInfo-container-item">
            <el-col :span="12">
              <el-select v-model="postForm.platform" placeholder="请选择系统">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-tooltip  class="item" effect="dark" content="请输入名称（限10个字符）" placement="top">
            <el-form-item label-width="110px" label="名称：" class="postInfo-container-item" prop="name">
              <el-col :span="12">
                    <el-input style="min-width:280px" placeholder="请输入名称（限10个字符）" maxlength="10" v-model="postForm.name">
                    </el-input>
              </el-col>
            </el-form-item>
          </el-tooltip>
          <el-form-item label-width="110px" label="顺序："  class="postInfo-container-item" prop="number">
            <el-col :span="12">
              <el-input-number  v-model="postForm.sort" :step="1"></el-input-number>
            </el-col>
          </el-form-item>
          <template v-if="postForm.feature == 'TOOL_CONFIG'">
            <el-tooltip  class="item" effect="dark" content="请输入跳转链接" placement="top">
              <el-form-item label-width="110px" label="跳转链接：" class="postInfo-container-item" prop="skipRemarks">
                <el-col :span="24">
                  <el-input  placeholder="请输入跳转链接" v-model="postForm.skipRemarks" @input.native='deleteSpace'>
                  </el-input>
                </el-col>
              </el-form-item>
            </el-tooltip>
          </template>
          <template v-else>
            <el-form-item label-width="110px" label="跳转类型：" class="postInfo-container-item" prop="skip">
              <el-col :span="12">
                <el-select v-model="postForm.skip" placeholder="请选择跳转类型">
                  <el-option
                    v-for="item in brandListOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <el-tooltip  class="item" effect="dark" :content="holderVal.placeholder" placement="top">
              <el-form-item label-width="110px" :label="holderVal.name" class="postInfo-container-item" prop="skipRemarks" >
                <el-col :span="24">
                  <el-input  :placeholder="holderVal.placeholder" v-model="postForm.skipRemarks" @input.native='deleteSpace'>
                  </el-input>
                </el-col>
              </el-form-item>
            </el-tooltip>
          </template>
          <el-form-item label-width="110px" label="是否全版本：" class="postInfo-container-item">
            <el-col :span="12">
              <el-select v-model="isChoAll" placeholder="请选择全版本">
                <el-option
                  v-for="item in choAllOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label-width="110px" label="版本："  class="postInfo-container-item" prop="number" v-show="!isChoAll">
            <el-col :span="24">
              <el-select  style="width:100%" v-model="version" multiple placeholder="请选择">
                <el-option
                  v-for="item in versionListOptions"
                  :key="item.val"
                  :label="item.name"
                  :value="item.val">
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label-width="110px" label="活动时间：" class="postInfo-container-item" prop="time">  
            <el-col :span="12">
              <el-date-picker
                v-model="time"
                type="datetimerange"
                :picker-options="pickerOptions2"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label-width="110px" label="图片：" class="postInfo-container-item">
            <el-col :span="12">
                <el-upload
                :headers="headers"
                action="/tools/oss/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleUploadSuccess"
                list-type="picture"
                 :file-list="fileList"
                :limit="1">
                <el-button size="small" type="primary" icon="el-icon-upload2">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">注：建议尺寸：{{ postForm.feature == 'TOOL_CONFIG' ? '96X96px' : postForm.feature == 'EXPERT_BANNERS' ? '972X382px' : postForm.feature == 'LIVE_BANNERS' ? '976X468px' : '像素 1029 * 444 长宽比 2.31'}}</div>
              </el-upload>
            </el-col>
          </el-form-item>
          <el-form-item class="leftPaddingChange">
            <el-button  type="primary" size="small" @click="submitForm()">保存</el-button>
            <el-button  size="small" @click="cancelChangeLesson()" plain>取消</el-button>
          </el-form-item>
        </el-col>
      </div>
    </el-form>
    <el-dialog title="升学端消息推送" :visible.sync="dialogTableVisible">
      <el-input size="small" @keyup.enter.native="handleFilter" style="width: 200px;margin-left: 10px" class="filter-item" placeholder="请输入手机号" v-model="listQuery.mobile">
      </el-input>
      <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
     <!--  <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-success" @click="saveUser">保存</el-button> -->
      <el-table :data="list"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- <el-table-column property="date" label="日期" width="150"></el-table-column> -->
        <el-table-column property="nickName" label="用户名" width="200"></el-table-column>
        <el-table-column property="mobile" label="手机号"></el-table-column>
      </el-table>
      <div v-show="!listLoading" style="margin-top:30px">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo"
          :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background>
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/headImage'
import MDinput from '@/components/MDinput'
import Multiselect from 'vue-multiselect' // 使用的一个多选框组件，element-ui的select不能满足所有需求
import 'vue-multiselect/dist/vue-multiselect.min.css' // 多选框组件css
import { validateURL } from '@/utils/validate'
import { getToken } from '@/utils/auth' // 验权
import { getList, delId, delIds, update, getAreaList, getVersions, getId, toggleId, add } from '@/api/activity'

export default {
  name: 'articleDetail',
  components: { Tinymce, MDinput, Upload, Multiselect },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: this.i18n[rule.field] + '为必填项',
          type: 'error',
          duration: 1000
        })
        callback(new Error(this.i18n[rule.field] + '为必填项'))
      } else {
        callback()
      }
    }
    const validateArrRequire = (rule, value, callback) => {
      if (value.length === 0) {
        this.$message({
          message: this.i18n[rule.field] + '为必填项',
          type: 'error'
        })
        callback(new Error(this.i18n[rule.field] + '为必填项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validateURL(value)) {
          callback()
        } else {
          this.$message({
            message: 'url填写不正确',
            type: 'error'
          })
          callback(new Error(this.i18n[rule.field] + '为必填项'))
        }
      } else {
        this.$message({
          message: this.i18n[rule.field] + '为必填项',
          type: 'error'
        })
        callback(new Error(this.i18n[rule.field] + '为必填项'))
      }
    }

    return {
      areaOptions: [], // 省份列表
      isIndexBanner: true, // 是否是首页banner
      version:[],
      versionListOptions:[],
      headers:{},
      holderVal:{
        placeholder:'请输入商品ID',
        name:'商品ID：'
      },
      holderMap:{
        'lesson_detail':{
          placeholder:'请输入商品ID',
          name:'商品ID：'
        },
        'infomation_detail':{
          placeholder:'请输入资讯ID',
          name:'资讯ID：'
        },
        'url':{
          placeholder:'请输入跳转链接',
          name:'跳转链接：'
        }
      },
      pickerOptions:{
        disabledDate(time){
          const date = new Date()
          return time.getTime() < date.getTime() || time.getTime() > (date.getTime() + 3600 * 1000 * 24 * 7)
        }
      },
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      time:'',
      multipleSelection:[],
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        mobile:'',
        pageNo: 1,
        pageSize: 10
      },
      radio:'1',
      fileList:[],
      dialogTableVisible:false,
      /*fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],*/
      tagValue:'',
      words:100,
      dataObj: { token: '', key: '' },
      dataObjOriginal: { token: '', key: '' },
      postForm: {
        feature:'HOMEPAGE_BANNERS',
        id:'',
        apiVersion:[],
        sort:1,
        image:'',
        name:'',
        platform:'ALL',
        skipRemarks:'',
        skip:'lesson_detail',
        areaName: ''
      },
      fetchSuccess: true,
      loading: false,
      brandListOptions: [{
        id:'lesson_detail',
        name:'课程'
      }, {
        id:'infomation_detail',
        name:'资讯'
      }, {
        id:'url',
        name:'网页'
      }],
      options:[{
        value: 'ALL',
        label: '所有'
      }, {
        value: 'IOS_IPHONE',
        label: 'iOS'
      }, {
        value: 'AM',
        label: '安卓'
      }],
      featureOptions: [{
        value: 'HOMEPAGE_BANNERS',
        label: '首页Banner'
      }, {
        value: 'LIVE_BANNERS',
        label: '课程Banner'
      }, {
        value: 'EXPERT_BANNERS',
        label: '专家Banner'
      }, {
        value: 'RESEARCH_BANNERS',
        label: '研学Banner'
      }, {
        value: 'TOOL_CONFIG',
        label: '工具页'
      }],
      rules: {
        skip: [{ required: true, message: '跳转类型必选', trigger: 'change' }],
        // areaName: [ { required: true, message: '投放区域必选', trigger: 'change' } ],
        name: [{ required: true, message: '名称必填', trigger: 'blur' }],
        skipRemarks: [
          { required: true, message: '内容必填', trigger: 'blur' }
          // { validator: deleteSpace, message:'url非法', trigger:'change'}
        ]
      },
      isChoAll: false,
      choAllOption: [{
        value: true,
        label: '是'
      }, {
        value: false,
        label: '否'
      }]
    }
  },
  watch: {
    'postForm.skip'(val){
      this.holderVal = this.holderMap[val]
    },
    'postForm.feature'(val){
      if(val == 'TOOL_CONFIG'){
        this.postForm['skip'] = 'url'
      }else{
        //this.postForm['skip'] = 'lesson_detail'
      }
    },
    isChoAll(boolean) {
      if (boolean) {
        this.version = []
      }
    }
    // 'postForm.skipRemarks'(val,old){
    //   this.postForm.skipRemarks = val.replace(' ','')
    // }
  },
  mounted() {
    const date = new Date()
    this.getVersions()
    this.fetchAreaData()
    this.headers = { accessToken:getToken() }
    this.time = [date, new Date(date.getTime() - 1000 + (3600 * 1000 * 24 * 7))]
  },
  methods: {
    fetchAreaData() {
      getAreaList().then(response => {
        this.areaOptions = response.data
        this.areaOptions.unshift({
          value: 100001,
          label: '全国',
          children: []
        })
      })
    },
    deleteSpace(e){
      // this.postForm.skipRemarks = value.replace(/\s/g,'')

      this.$nextTick(() => {
        this.postForm.skipRemarks = e.target.value.replace(/\s/g, '')
      })
    },
    cancelChangeLesson() {
      this.$refs.postForm.resetFields()
    },
    formatDate(now) {
      var year = now.getFullYear()
      var monthValue = now.getMonth() + 1
      var month = monthValue < 10 ? '0' + monthValue : monthValue
      var date = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()
      var hour = now.getHours() < 10 ? '0' + now.getHours() : now.getHours()
      var minute = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()
      var second = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds()
      return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
    },
    getVersions() {
      getVersions().then(response => {
        const { code, data } = response
        if(code == 0){
          const versionList = []//[{name:'所有',val:'all'}];
          data.map(e => versionList.push({ name:e, val:e }))
          this.versionListOptions = versionList
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    saveUser(){
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getUserList()
    },
    getUserList() {
      this.listLoading = true
      const params = this.listQuery
      getUserList(params).then(response => {
        const { code, data:{ total, list } } = response
        if(code == 0){
          this.total = total
          this.list = list
          this.listLoading = false
        }
      })
    },
    handleUploadSuccess(rst){
      const { code, data:{ picUrlList } } = rst
      const { postForm } = this
      if(code == 0){
        postForm['image'] = picUrlList[0]
        this.postForm = postForm
      }
    },
    handlePreview(file) {
    },
    handleClose(tag) {
      this.multipleSelection.splice(this.multipleSelection.indexOf(tag), 1)
    },
    handleRemove(file, fileList) {
      this.postForm['image'] = ''
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getUserList()
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          const params = this.postForm
          const { postForm:{ skip, skipRemarks }, time, version } = this
          if(!time){
            this.$notify({
              message: '活动时间必填',
              type: 'error',
              duration: 1000
            })
            this.loading = false
            return
          }
          if(skip == 'lesson_detail' || skip == 'infomation_detail'){
            const skiptext = this.holderMap[skip].name.replace('：', '')
            if(!/^\d+$/.test(skipRemarks.trim())){
              this.$notify({
                message: skiptext + '必须是数字',
                type: 'error',
                duration: 1000
              })
              this.loading = false
              return
            }
          }else if(skip == 'url'){
            if(!validateURL(skipRemarks.trim())){
              this.$notify({
                message: '请输入正确的url',
                type: 'error',
                duration: 1000
              })
              this.loading = false
              return
            }
          }
          if(this.isChoAll){
            params['apiVersion'] = 'all'
          }else{
            params['apiVersion'] = version.join(',')
          }
          if (params.feature !== 'HOMEPAGE_BANNERS') {
            params['areaName'] = ''
          }
          params['startTime'] = time[0]
          params['endTime'] = time[1]
          add(params).then(response => {
            const { code, message } = response
            if (code == 0) {
              this.$notify({
                title: '成功',
                message: '活动发布成功',
                type: 'success',
                duration: 1000
              })
              this.loading = false
              this.$router.push({ path: '/activity/table' })
            }else{
              this.$notify({
                message: message,
                type: 'error',
                duration: 1000
              })
            }
          }).catch(err => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import 'src/styles/mixin.scss';
$left-offset:96px;
@mixin leftChange {
  padding-left:$left-offset;
  padding-top: 30px;
  box-sizing:content-box;
  @media screen and (max-width: 1205px){
    padding-left:0;
    box-sizing:border-box;
  }
}
.leftPaddingChange{
  @include leftChange;
  button{
    min-width:100px;
  }
}
.upload-img-dev{
  width:320px;
  height:160px;
  position: absolute;
  right: 200px;
  bottom: 60px;
  z-index: 3;
}
.upload-img{
  width:320px;
  height:160px;
}
.tagLeft{
  margin-left:10px;
}
.title-prompt {
  position: absolute;
  right: 0px;
  font-size: 12px;
  top: 10px;
  color: #ff4949;
}
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
    .editor-container {
      min-height: 500px;
      .editor-upload-btn-container {
        text-align: right;
        margin-right: 10px;
        .editor-upload-btn {
          display: inline-block;
        }
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>